<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us">
<head>
  <title>
    2. [译]多线程的优点 // 飞狐的部落格
  </title>

  <link href="http://gmpg.org/xfn/11" rel="profile">
<meta http-equiv="content-type" content="text/html; charset=utf-8">


<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

<meta name="description" content="本文介绍了多线程的优点">
<meta name="keywords" content="java concurrency,">
<meta name="author" content="飞狐">
<meta name="generator" content="Hugo 0.14" />

  <meta property="og:title" content="2. [译]多线程的优点" />
<meta property="og:description" content="本文介绍了多线程的优点" />
<meta property="og:type" content="website" />
<meta property="og:locale" content="en_US" />
<meta property="og:url" content="http://lucumt.info/posts/java-concurrency/multithreading-benefits/" />


  
   <link rel="stylesheet" href="http://lucumt.info/css/base-min.css">
   <link rel="stylesheet" href="http://lucumt.info/css/pure-min.css">
  
  
    <link rel="stylesheet" href="http://lucumt.info/css/grids-responsive-min.css">
  
  

  <link rel="stylesheet" href="http://lucumt.info/css/redlounge.css">
  
  <link rel="stylesheet" href="http://lucumt.info/css/googleapis.font.css">
  <link rel="stylesheet" href="http://lucumt.info/css/jqcloud.css">
  <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
  

  
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://lucumt.info/touch-icon-144-precomposed.png">
  <link rel="shortcut icon" href="http://lucumt.info/lucumt.ico">

  
  <link href="" rel="alternate" type="application/rss+xml" title="飞狐的部落格" />

  <script src="http://lucumt.info//js/jquery.min.js"></script>
  <script src="http://lucumt.info//js/jqcloud-1.0.4.min.js"></script>

    
  
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.6.0/styles/rainbow.min.css">
  
  <script src="http://lucumt.info/js/highlight.min.js"></script>
  <script>hljs.initHighlightingOnLoad();</script>


  

  

  

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', "UA-75123653-1", 'auto');
  ga('send', 'pageview');
</script>




<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?cabc0a71f63da092412d82d1aefe7d1c";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>

</head>
<body>
	
		<div id="nav-to-top">
			<span class="decorative-marker">//</span><a href="#top">返回顶部</a>
		</div>
	

	<div id="layout" class="pure-g">
    
		 <a href="https://github.com/lucumt/ghblog" target="_new">
			<img style="position: absolute; top: 0; right: 0; border: 0;" 
			src="/img/forkme_right_red.png" alt="Fork me on GitHub">
		</a>

    <div class="sidebar pure-u-1 pure-u-md-1-4">
  <div class="header">
    

	
	  <img src="http://lucumt.info/img/photo.jpg" class="profilepic">
	

    <h1 class="brand-title">飞狐的部落格</h1>
    <h2 class="brand-tagline">Rosen Lu</h2>

    <nav class="nav">
      <ul class="nav-list">
        <li class="nav-item"><span class="nav-item-separator">//</span><a href="http://lucumt.info/">Home</a></li>
        
          <li class="nav-item"><span class="nav-item-separator">//</span><a href="http://lucumt.info/about/">About</a></li>
        
          <li class="nav-item"><span class="nav-item-separator">//</span><a href="http://lucumt.info/posts/">Blog</a></li>
        
      </ul>
    </nav>

    
    <div class="social-buttons">
      
        
        <a href="https://github.com/lucumt" target="_blank"><i class='fa fa-github'></i></a>
        
      
        
        <a href="https://plus.google.com/u/0/115794588502118898127/posts" target="_blank"><i class='fa fa-google-plus'></i></a>
        
      
        
        <a href="https://www.facebook.com/rosen.lu.1" target="_blank"><i class='fa fa-facebook'></i></a>
        
      
        
        <a href="http://www.twitter.com/rosenlucumt" target="_blank"><i class='fa fa-twitter'></i></a>
        
      
        
        <a href="mailto:lucumt@gmail.com" target="_blank"><i class='fa fa-mail-forward'></i></a>
        
      
    </div>
    
    
	
	  <hr class="nav-site-separator"/>
	  <nav class="nav">
      <ul class="nav-list">
	    
		   <li class="nav-site"><a href="http://lilydjwg.is-programmer.com/" target="_blank">依云的博客</a></li>
		
		   <li class="nav-site"><a href="http://evilbinary.org/" target="_blank">邪恶二进制</a></li>
		
		   <li class="nav-site"><a href="http://www.wlman.cc/" target="_blank">Consec &#39;s Blog</a></li>
		
		   <li class="nav-site"><a href="http://www.linuxzen.com/" target="_blank">cold&#39;s world</a></li>
		
		   <li class="nav-site"><a href="http://frantic1048.logdown.com/" target="_blank">Frantic log#1048</a></li>
		
	  </ul>
	  </nav>
	
	

  </div>
</div>

	
	

    <div class="content pure-u-1 pure-u-md-3-4">
		<a name="top"></a>
		

		
			
		    <div id="toc" class="pure-u-1 pure-u-md-1-4">
				<small class="toc-label">Contents</small>
		   	 	<nav id="TableOfContents">
<ul>
<li>
<ul>
<li><a href="#更好的资源利用:03f2a6ff6ff43564d8cd77dcf4ddb389">更好的资源利用</a></li>
<li><a href="#简化程序设计:03f2a6ff6ff43564d8cd77dcf4ddb389">简化程序设计</a></li>
<li><a href="#提高程序响应:03f2a6ff6ff43564d8cd77dcf4ddb389">提高程序响应</a></li>
</ul></li>
</ul>
</nav>
		    </div>
		    
	    
  		<section class="post">
            <h1 class="post-title">
              <a href="http://lucumt.info/posts/java-concurrency/multithreading-benefits">2. [译]多线程的优点</a>
            </h1>
            <h3 class="post-subtitle">
            	
            </h3>
            
            	<span class="post-date">
                	<span class="post-date-day"><sup>1</sup></span><span class="post-date-separator">/</span><span class="post-date-month">Apr</span> <span class="post-date-year">2017</span>
            	</span>
            	
            
            	
            		<span class="post-author-single">By <a class="post-author" href="https://www.linkedin.com/in/%E8%BF%90%E5%BC%BA-%E5%8D%A2-50a08bb5/" target="_new">飞狐</a></span>
            		




            	
            

			
			
				<div class="post-categories">
				
					<a class="post-category post-category-java" href="http://lucumt.info//categories/java">Java</a>
				
					<a class="post-category post-category-java-concurrency" href="http://lucumt.info//categories/java-concurrency">Java Concurrency</a>
				
					<a class="post-category post-category-%E7%BF%BB%E8%AF%91" href="http://lucumt.info//categories/%E7%BF%BB%E8%AF%91">翻译</a>
				
				</div>
			

			

			

            

<p>本文翻译自<strong><a href="http://tutorials.jenkov.com/java-concurrency/benefits.html">Java Concurrency / Multithreading Benefits</a></strong></p>

<p>尽管多线程给程序实现带来了挑战，但由于多线程的一些优点我们仍然在使用它，其中的一些优点如下：</p>

<ul>
<li>更好的资源利用</li>
<li>在某些场景可以简化程序设计</li>
<li>提高程序响应</li>
</ul>

<h2 id="更好的资源利用:03f2a6ff6ff43564d8cd77dcf4ddb389">更好的资源利用</h2>

<p>假设我们有一个程序从本地磁盘中读取和处理文件，若读取和处理一个文件的耗时分别为5秒钟和2秒钟，则读取处理2个文件的耗时如下：</p>

<pre><code>5 seconds reading file A
2 seconds processing file A
5 seconds reading file B
2 seconds processing file B
-----------------------
14 seconds total//串行读取时总共耗时14秒
</code></pre>

<p>当从磁盘读取文件时CPU的大部分时间都花费在等待从磁盘读取数据，在此期间CPU大部分时间都处于空闲状态。这些空闲时间可以做一些其它的事情，通过改变操作顺序，CPU可以被更好的利用，如下面的列子：</p>

<pre><code>5 seconds reading file A
5 seconds reading file B + 2 seconds processing file A
2 seconds processing file B
-----------------------
12 seconds total//并行读取时总共耗时12秒
</code></pre>

<p>在上面的例子中，CPU先等待读取第一个文件，然后开始读取第二个文件，在读取第二个文件的同时，CPU可以同时处理第一个文件。请记住，当等待从磁盘读取数据时，CPU大部分时间处于空闲状态！</p>

<p>通常情况下，CPU在等待IO响应时可以做一些其它事情，这不仅适用于磁盘IO操作，也适用于网络IO操作，或者读取用户输入,网络和磁盘IO操作通常比CPU和内存IO操作慢很多。</p>

<h2 id="简化程序设计:03f2a6ff6ff43564d8cd77dcf4ddb389">简化程序设计</h2>

<p>如果在单线程应用程序中编程实现上述读取和处理文件的功能，就必须跟踪每个文件的读取和处理状态。相反的，在多线程程序中我们可以开启两个线程，每个线程读取和处理同一个文件。每个线程在等待从磁盘读取文件时都会被阻塞，但在等待的同时，其它线程可以利用CPU来处理已经读取的文件。这样能够是的CPU和磁盘都被更好的使用，而且由于每个线程只需要跟踪一个文件，编程实现也会变得更简单。</p>

<h2 id="提高程序响应:03f2a6ff6ff43564d8cd77dcf4ddb389">提高程序响应</h2>

<p>将单线程应用变为多线程应用的另一个常见目的是获得更快的响应。假设有一个服务器程序在某个端口监听请求，当接收到一个请求后，服务器处理该请求，处理完后再继续监听，该循环监听服务器的设计草图如下：</p>

<pre><code>while(server is active){
    listen for request //监听请求
    process request//处理请求
}
</code></pre>

<p>如果某个请求需要花费很长的时间来处理，那么在此期间其它的客户端就不能向此服务器发送请求，只有当服务器处于监听状态时才能够接收请求。</p>

<p>一种替代方案是让监听线程将接收到的请求发送给worker线程处理，然后立即恢复监听，worker线程对请求进行处理并给客户端发送回复，此种服务器的设计草图如下：</p>

<pre><code>while(server is active){
    listen for request //监听请求
    hand request to worker thread//将接收到的请求发送给worker线程处理
}
</code></pre>

<p>在这种方式下，服务器线程会迅速返回监听，因而更多的客户端可以给服务器发送请求，服务器的响应也得以提高。</p>

<p>该方法同样适用于桌面应用程序，如果你点击一个按钮来开启一个长任务，而执行该任务的线程是更新窗口、按钮等部件的线程，那么在该任务运行期间，该桌面程序将无法响应其它操作。相反的，可以将该任务移交给一个worker线程，当worker线程处理该任务时，更新窗口的线程处于空闲状态，可以响应其它用户请求，当worker线程执行完任务时通知更新窗口线程，该窗口线程根据执行结果来更新程序。因而利用worker线程设计实现的程序对用户更具有响应性。</p>

<p>&lt;–翻译结束!–&gt;</p>

	
			

			

			
          </section>
		  
		  <div class="page-link">
			
			<a href="http://lucumt.info/posts/java-concurrency/java-concurrency-multithreading-tutorial/">//下一篇</a>
			
			&nbsp;
			
			<a class="page-link-right" href="http://lucumt.info/posts/java-concurrency/multithreading-costs/">//上一篇</a>
			
	      </div>

          
          	<div id="disqus_thread"></div>
<script type="text/javascript">
    var disqus_shortname = 'rosenlu';
    var disqus_identifier = 'http:\/\/lucumt.info\/posts\/java-concurrency\/multithreading-benefits\/';
    var disqus_title = '2. [译]多线程的优点';
    var disqus_url = 'http:\/\/lucumt.info\/posts\/java-concurrency\/multithreading-benefits\/';

    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
          
        
      <div class="footer">
	<hr class="thin" />
	<div class="pure-menu pure-menu-horizontal pure-menu-open">
		<ul class="footer-menu">
		
			<li><a href="https://github.com/tmaiaroto/hugo-redlounge">Designed by Red Lounge</a></li>
		
		</ul>
	</div>

	<p>&copy; 2017. All rights reserved.</p>
</div>
    </div>
  </div>
	
		<script type="text/javascript">
			onscroll = function() {
			  var toTopVisible = false;
			  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
			  if (scrollTop > 1000) {
			    if (!toTopVisible) {
			      document.getElementById('nav-to-top').style.display = 'block';
			    }
			  } else {
			    if (scrollTop < 1000 || toTopVisible) {
			      document.getElementById('nav-to-top').style.display = 'none';
			    }
			  }
			};
		</script>
	

	

  
</body>
</html>